import { ElLoading, type LoadingOptions } from 'element-plus'

class LoadingManager {
  private static instance: LoadingManager
  private count: number = 0
  private loadingInstance: ReturnType<typeof ElLoading.service> | null = null

  // 单例模式
  private constructor() {}

  public static getInstance(): LoadingManager {
    if (!LoadingManager.instance) {
      LoadingManager.instance = new LoadingManager()
    }
    return LoadingManager.instance
  }

  // 显示加载状态
  public showLoading(options: LoadingOptions = { lock: true, text: '加载中...' }): void {
    if (this.count === 0) {
      this.loadingInstance = ElLoading.service(options)
    }
    this.count++
  }

  // 隐藏加载状态
  public hideLoading(): void {
    this.count--
    if (this.count <= 0 && this.loadingInstance) {
      this.loadingInstance.close()
      this.count = 0
      this.loadingInstance = null
    }
  }

  // 高阶函数：用于封装异步请求
  public withLoading<T>(fn: () => Promise<T>, options: LoadingOptions = {}): Promise<T> {
    this.showLoading(options)
    return fn().finally(() => this.hideLoading())
  }
}

export const loadingManager = LoadingManager.getInstance()
